import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'

// 创建axios实例
const http = axios.create({
  // baseURL: 'http://localhost:8080/api',
  baseURL: 'https://0ce4-112-10-130-177.ngrok-free.app/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 不需要认证的API白名单
const WHITELIST_URLS = ['/auth/login', '/auth/register', '/auth/register/verify`']

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 检查URL是否在白名单中
    const isWhitelisted = WHITELIST_URLS.some((url) => config.url?.includes(url))

    if (!isWhitelisted) {
      // 添加认证token
      const token = localStorage.getItem('token')
      if (token) {
        config.headers = config.headers || {}
        config.headers.Authorization = `Bearer ${token}`
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    // 当code === 200时，返回数据
    if (response.data.code === 200) {
      return response.data.data
    } else {
      // 当不是200时报错，报错的信息就是response.data.message
      return Promise.reject(new Error(response.data.message || '请求失败'))
    }
  },
  (error) => {
    // 处理网络错误等
    return Promise.reject(error)
  },
)

/**
 * 封装的HTTP请求方法
 */
export default {
  get<T>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {
    return http.get(url, { params, ...config })
  },

  post<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return http.post(url, data, config)
  },

  put<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return http.put(url, data, config)
  },

  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return http.delete(url, config)
  },
}
